package org.linlinjava.litemall.core.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class TimeUtils {

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String getUnixTime(Date date) {
        long times = date.getTime();
        long unixTimes = times / 1000;
        return String.valueOf(unixTimes);
    }

    public static Date parseDateStr(String dateStr, String pattern) {
        LocalDateTime localDateTime = convertStringToLDT(dateStr, pattern);
        return toDate(localDateTime);
    }

    public static String fromDate(Date date) {
        return formatDateTime(date, TimeUtils.DEFAULT_PATTERN);
    }

    public static Date toDate(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        Date date = Date.from(instant);
        return date;
    }

    public static LocalDateTime convertStringToLDT(String date, String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(date, df);
    }

    public static String formatDateTime(Date dateTime, String pattern) {
        LocalDateTime time = convertDateToLDT(dateTime);
        return formatTime(time, pattern);
    }

    public static LocalDateTime convertDateToLDT(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    public static String formatTime(LocalDateTime time, String pattern) {
        return DateTimeFormatter.ofPattern(pattern).format(time);
    }

    public static Boolean isAfter(LocalDateTime time1, LocalDateTime time2) {
        return time1.isAfter(time2);
    }

    public static Boolean isBefore(LocalDateTime time1, LocalDateTime time2) {
        return time1.isBefore(time2);
    }

}
